package com.zr.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CreateImageAction extends HttpServlet{

	private static final int WIDTH = 120;// 验证码的宽度
	private static final int HEIGHT = 40;// 验证码的高度

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
		Graphics g = bi.getGraphics(); // 绘制图片
		Random r = new Random();
		Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)); // 图片的背景颜色
		g.setColor(c);
		g.fillRect(0, 0, WIDTH, HEIGHT); // 画一个框
		char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
		int len = ch.length;
		int index;// 获得的随机位置
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 4; i++) {
			index = r.nextInt(len);// 随机获取一个
			g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));// 取出字符的颜色
			g.setFont(new Font("宋体", Font.BOLD, 40));
			g.drawString(ch[index] + "", (i * 25 + 10), HEIGHT - 5);
			sb.append(ch[index]);
		}
		g.setColor(Color.GREEN);
		for (int i = 0; i < 5; i++) {
			int x1 = r.nextInt(WIDTH);
			int y1 = r.nextInt(HEIGHT);
			int x2 = r.nextInt(WIDTH);
			int y2 = r.nextInt(HEIGHT);
			g.drawLine(x1, y1, x2, y2);
		}
		g.setColor(Color.BLUE);
		for(int j = 0;j<70;j++){
			g.setFont(new Font("宋体",Font.BOLD,10));
			g.drawString(".", r.nextInt(WIDTH), r.nextInt(HEIGHT));
		}
		request.getSession().setAttribute("piccode", sb.toString());
		ImageIO.write(bi, "JPG", response.getOutputStream());

	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}
	
}
